import { Ast } from "../ast";
import { isRedOpen } from "../pages";
import { getLiveRoomRedPackets } from "./LiveRoomRedPacketInfoVisitor";
import { RedOpenContext, RedOpenVisitor } from "./RedOpen";
import { clickSend } from "./send";

export class RedOpenJoinVisitor extends RedOpenVisitor {
    visitButton(node: Ast, ctx: any) {
        if (node.id.endsWith(`action`) && node.text === `进入直播间`) {
            node.click()
            return;
        }
    }
    visitFrameLayout(node: Ast, ctx: RedOpenContext) {
        if (!node.visibleToUser) return;
        if (isRedOpen()) {
            const redPackets = getLiveRoomRedPackets(node)
            if (redPackets && redPackets.list.length > 0) {
                const uiSetting = ctx.setting;
                const reds = redPackets.list.filter(red => {
                    if (red.type === `快币`) {
                        if (uiSetting.red_type_kuai_bi) {
                            return true;
                        }
                        return false;
                    }
                    if (red.type === '口令') {
                        if (uiSetting.red_type_kou_ling) {
                            return true;
                        }
                        return false;
                    }
                    if (red.type === `穿云箭`) {
                        if (uiSetting.red_type_chuan_yun_jian) {
                            return true;
                        }
                        return false;
                    }
                    if (red.type === `粉丝`) {
                        if (uiSetting.red_type_fen_si) {
                            return true;
                        }
                        return false;
                    }
                    if (red.type === `分享`) {
                        if (uiSetting.red_type_fen_xiang) {
                            return true;
                        }
                        return false;
                    }
                    return false;
                }).sort((a, b) => a.count - b.count)
                if (reds.length <= 0) {
                    events.broadcast.emit('UPDATE', `没有满足条件的红包`)
                    ctx.status = 'fail'
                    return;
                }
                ctx.status = `opening`
                reds.map(red => {
                    if (typeof red.join === 'function') {
                        red?.join()
                        sleep(1000)
                        if (red.type === '口令') {
                            clickSend()
                        }
                    }
                })
            }
        }
        // 检查是否有弹框
        node.children.map(child => child.visit(this, ctx))
    }
}